package com.fxkj.cloud.drms.infra.persistence.dao;

import com.fxkj.cloud.drms.infra.persistence.po.AlarmHistoryPO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * <p>description: </p>
 * @author ww
 * @date 2025/4/7 15:29
 */
public interface AlarmHistoryJpaRepository extends JpaRepository<AlarmHistoryPO, UUID>, JpaSpecificationExecutor<AlarmHistoryPO> {

    List<AlarmHistoryPO> findByDeviceSerialNoAndAlarmCodeAndClosed(String deviceSerialNo, String alarmCode, Boolean closed);

    @Query(value = "select A.alarm_level,A.alarm_count from (" +
            "SELECT alarm_level,alarm_code,COUNT(DISTINCT (device_id, alarm_code,end_ts)) AS alarm_count " +
            "FROM t_alarm_history " +
            "WHERE product_id in ?1 " +
            "GROUP BY GROUPING SETS ((alarm_level, alarm_code), (alarm_level)) " +
            "ORDER BY alarm_level, alarm_code NULLS FIRST) A " +
            "WHERE A.alarm_code IS NULL", nativeQuery = true)
    List<Map<String, Object>> alarmStatisticsByProductIdIn(@Param("productId") Set<UUID> productIds);
}
